<template>
  <view class="page-container">
    <view class="header pb-120rpx">
      <uni-nav-bar
        title="店铺中心"
        fixed
        :border="false"
        background-color="transparent"
      />
      <view class="content p-32rpx">
        <view class="flex gap-16rpx items-center">
          <image
            :src="merchantInfo?.storeLogo"
            class="w-100rpx h-100rpx rounded-50%"
            mode="aspectFill"
          ></image>
          <view class="flex flex-col justify-between flex-1">
            <view class="name">
              <text v-if="merchantLoading">加载中...</text>
              <text v-else>{{
                merchantInfo?.merchantName ||
                storeStore.merchantName ||
                "未选择店铺"
              }}</text>
            </view>
            <view class="account text-24rpx">{{
              merchantInfo?.userMobile ||
              merchantInfo?.userName ||
              userStore.userInfo?.phone ||
              userStore.userInfo?.username ||
              "未知"
            }}</view>
          </view>
          <view class="self-start">
            <view class="text-28rpx" :style="{ color: businessStatus.color }">
              {{ businessStatus.status }}
            </view>
          </view>
        </view>
      </view>
    </view>
    <view
      class="assets mt--100rpx mx-32rpx bg-#fff rounded-16rpx px-32rpx py20rpx"
      @click="goToBalance"
    >
      <view class="mb-12rpx"
        >账户总览
        <uni-icons type="right" color="#999"></uni-icons>
      </view>
      <view class="flex justify-between">
        <view class="flex flex-col">
          <view class="color-#999 text-28rpx">总资产</view>
          <view v-if="overviewLoading" class="text-24rpx color-#999"
            >加载中...</view
          >
          <view v-else class="">¥ {{ accountOverview.totalAsset }}</view>
        </view>
        <view class="flex flex-col">
          <view class="color-#999 text-28rpx">昨日收入</view>
          <view v-if="overviewLoading" class="text-24rpx color-#999"
            >加载中...</view
          >
          <view v-else class="">¥ {{ accountOverview.yesterdayIncome }}</view>
        </view>
      </view>
    </view>
    <scroll-view class="scroll-content" :scroll-y="true">
      <view
        class="banner m-32rpx rounded-20rpx h-240rpx"
        @click="goToValueAddedService"
      ></view>
      <view class="capabilities mx-32rpx">
        <view
          class="level px-20rpx mx-20rpx h-88rpx mt-20rpx rounded-t-12rpx flex justify-between"
          @click="goToLevelCenter"
        >
          <view class="line-height-88rpx color-#fff4e1">等级中心</view>
          <view
            class="color-#fff4e1 text-24rpx line-height-88rpx flex items-center"
            >查看等级
            <uni-icons type="right" color="#fff4e1"></uni-icons>
          </view>
        </view>
      </view>
      <view
        class="service p-20rpx bg-#fff mx-32rpx rounded-12rpx justify-between content-between"
      >
        <view class="text-28rpx">功能服务</view>
        <view class="grid grid-cols-4 grid-rows-2">
          <view
            v-for="item in serviceOptions"
            :key="item.value"
            class="flex flex-col items-center"
            @click="handleServiceClick(item)"
          >
            <image
              :src="`/static/icon/${item.icon}.png`"
              mode="aspectFit"
              class="w-80rpx h-80rpx block"
            ></image>
            <view class="text-24rpx">{{ item.label }}</view>
          </view>
        </view>
      </view>
      <view class="pb-66rpx">
        <view class="btn" @click="goToSwitchStore">切换店铺</view>
        <view class="btn color-#ff000e" @click="handleLogout">退出登录</view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { onShow } from "@dcloudio/uni-app";
import { useRequest } from "ahooks-vue";
import { serviceOptions } from "@/pages/mine/options";
import { removeToken } from "@/utils/request";
import { useStoreStore } from "@/store/modules/store";
import { useUserStore } from "@/store/modules/user";
import {
  getAccountOverview,
  getMerchantInfo,
  getUserInviteQrCode,
} from "@/api/mine";
import { dateUtils } from "@/utils/dayjs";

// 使用 Pinia store
const storeStore = useStoreStore();
const userStore = useUserStore();

// 商户详细信息
const merchantInfo = ref(null);

// 账户总览数据
const accountOverview = ref({
  totalAsset: "0.00", // 总资产
  yesterdayIncome: "0.00", // 昨日收益
});

// 计算营业状态
const businessStatus = computed(() => {
  // 获取营业时间，格式可能是 "09:00-22:00" 或 "09:00~22:00"
  const businessHours = merchantInfo.value?.storeBusinessHours || "";

  // 默认营业时间
  let openTime = "09:00";
  let closeTime = "22:00";

  // 解析营业时间
  if (businessHours) {
    // 支持 - 或 ~ 分隔符
    const timeArray = businessHours.split(/[-~]/);
    if (timeArray.length === 2) {
      openTime = timeArray[0].trim();
      closeTime = timeArray[1].trim();
    }
  }

  // 使用 dayjs 工具判断营业状态
  return dateUtils.getBusinessStatus(openTime, closeTime);
});

// 获取商户详细信息
const { loading: merchantLoading, run: fetchMerchantInfo } = useRequest(
  () =>
    getMerchantInfo({
      merchantId: storeStore.storeId,
      userId: userStore.userInfo?.userId,
    }),
  {
    manual: true,
    onSuccess: (response) => {
      console.log("获取商户信息成功：", response);
      if (response?.data) {
        merchantInfo.value = response.data;
        // 更新 store 中的商户名称
        if (response.data.merchantName) {
          storeStore.currentStore = {
            ...storeStore.currentStore,
            merchantName: response.data.merchantName,
          };
        }
      }
    },
    onError: (error) => {
      console.error("获取商户信息失败：", error);
    },
  },
);

// 获取账户总览
const { loading: overviewLoading, run: fetchAccountOverview } = useRequest(
  () =>
    getAccountOverview({
      merchantId: storeStore.storeId,
      userId: userStore.userInfo?.userId,
    }),
  {
    manual: true,
    onSuccess: (response) => {
      console.log("账户总览数据：", response);
      if (response?.data) {
        accountOverview.value = {
          totalAsset: response.data.a?.toFixed(2) || "0.00",
          yesterdayIncome: response.data.b?.toFixed(2) || "0.00",
        };
      }
    },
    onError: (error) => {
      console.error("获取账户总览失败：", error);
      uni.showToast({
        title: "获取账户信息失败",
        icon: "none",
      });
    },
  },
);

// 刷新我的页面数据
const refreshData = () => {
  console.log("🔄 刷新我的页面数据");

  // 从本地缓存恢复信息
  storeStore.hydrateFromStorage();
  userStore.hydrateFromStorage();

  console.log("店铺信息：", {
    merchantName: storeStore.merchantName,
    storeId: storeStore.storeId,
  });
  console.log("用户信息：", userStore.userInfo);

  // 获取商户详细信息和账户总览数据
  if (storeStore.storeId && userStore.userInfo?.userId) {
    fetchMerchantInfo();
    fetchAccountOverview();
  } else {
    console.warn("缺少 merchantId 或 userId，无法获取商户信息");
  }
};

// 页面显示时刷新数据（包括切换店铺后返回）
onShow(() => {
  refreshData();
});

// 跳转到账户余额页面
const goToBalance = () => {
  uni.navigateTo({
    url: "/pages/mine/balance/balance",
  });
};

// // 跳转到增值服务页面
// const goToValueAddedService = () => {
//   uni.navigateTo({
//     url: "/pages/mine/valueAddedService/valueAddedService",
//   });
// };

// 跳转到等级中心页面
const goToLevelCenter = () => {
  uni.showToast({
    title: "此功能开发中",
    icon: "none",
  });
  // uni.navigateTo({
  //   url: "/pages/mine/levelCenter/levelCenter",
  // });
};

// 跳转到切换店铺页面
const goToSwitchStore = () => {
  uni.navigateTo({
    url: "/pages/mine/switchStore/switchStore",
  });
};

// 退出登录
const handleLogout = () => {
  uni.showModal({
    title: "提示",
    content: "确定要退出登录吗？",
    confirmColor: "#ffbb00",
    success: (res) => {
      if (res.confirm) {
        // 清除登录状态
        try {
          // 1. 清除 token
          removeToken();

          // 2. 清除 Pinia store 信息
          storeStore.clearStoreInfo(); // 清除店铺信息
          userStore.clearUserInfo(); // 清除用户信息

          // 3. 清除其他可能存储的数据
          uni.removeStorageSync("storeInfo");
          uni.removeStorageSync("merchantInfo");

          console.log("已清除所有登录信息");

          // 显示退出成功提示
          uni.showToast({
            title: "已退出登录",
            icon: "none",
            duration: 1500,
          });

          // 延迟跳转，让用户看到提示
          setTimeout(() => {
            // 跳转到登录页面，使用 reLaunch 清空页面栈
            uni.reLaunch({
              url: "/pages/login/login",
            });
          }, 1500);
        } catch (error) {
          console.error("清除登录信息失败:", error);
          // 即使清除失败也跳转到登录页
          uni.reLaunch({
            url: "/pages/login/login",
          });
        }
      }
    },
  });
};

// 处理功能服务点击
const handleServiceClick = (item) => {
  console.log("点击功能服务:", item);

  // 根据不同的服务项跳转到不同的页面
  switch (item.value) {
    case "1": // 财务数据
      uni.navigateTo({
        url: "/pages/mine/financialData/financialData",
      });
      break;
    case "2": // 大额收款
      uni.navigateTo({
        url: "/pages/mine/largePayment/largePayment",
      });
      break;
    case "3": // 门店设置
      uni.navigateTo({
        url: "/pages/mine/storeSettings/storeSettings",
      });
      break;
    case "5": // 分享潮客
      getUserInviteQrCodeRun();
      break;
    case "7": // 收款码管理
      uni.navigateTo({
        url: "/pages/mine/paymentCode/paymentCodeManage",
      });
      break;
    case "11": // 发票服务
      uni.navigateTo({
        url: "/pages/mine/invoice/invoiceService",
      });
      break;
    case "12": // 店铺信息管理
      uni.navigateTo({
        url: "/pages/mine/storeInfo/storeInfo",
      });
      break;
    default:
      uni.showToast({
        title: item.label,
        icon: "none",
      });
      break;
  }
};
// 获取用户邀请二维码
const { run: getUserInviteQrCodeRun } = useRequest(
  () =>
    getUserInviteQrCode({
      merchantId: storeStore.storeId,
      userId: userStore.userId,
    }),
  {
    manual: true,
    onSuccess: (response) => {
      console.log("获取邀请二维码成功：", response);
      if (response?.data) {
        // 使用 uni.previewImage 预览图片
        uni.previewImage({
          urls: [response.data], // 图片URL数组
          current: response.data, // 当前显示的图片
        });
      } else {
        uni.showToast({
          title: "获取二维码失败",
          icon: "none",
        });
      }
    },
    onError: (error) => {
      console.error("获取邀请二维码失败：", error);
      uni.showToast({
        title: error.message || "获取二维码失败",
        icon: "none",
      });
    },
  },
);
</script>

<style lang="scss">
// 页面容器 - 适配 tabBar，确保不滚动
.page-container {
  height: calc(100vh - 50px - env(safe-area-inset-bottom, 0px)) !important;
  display: flex;
  flex-direction: column;
  overflow: hidden !important;
  background-color: #f5f5f5;
}

// 头部区域
.header {
  background: linear-gradient(to bottom, #ffbb00, #ffe898);
  flex-shrink: 0; // 不收缩
}

// 可滚动内容区域
.scroll-content {
  flex: 1; // 占据剩余空间
  height: 0; // 重要：让 flex 生效
}

// 底部安全距离
.safe-bottom {
  height: calc(
    40rpx + env(safe-area-inset-bottom, 0rpx)
  ); // 给内容底部留出空间，适配 iPhone 底部安全区域
}

// 其他样式
.banner {
  background: url("@/static/mine/banner.png") no-repeat center;
  background-size: cover;
  width: 686rpx;
  height: 240rpx;
}

.level {
  background: linear-gradient(to right, #394056, #1f2431);
}

.btn {
  background-color: #fff;
  text-align: center;
  line-height: 88rpx;
  height: 88rpx;
  margin-top: 32rpx;
}
.service {
  box-shadow: 0 0 20rpx 0 rgba(0, 0, 0, 0.1);
}
</style>
